<?php
	//create database
	function db_create_init($con, $dbname)
	{
		if (!$con) {
			echo "Could not connect the database";
			return $con;
		}
		$db_sql="create database " . $dbname;
		if (mysql_query($db_sql, $con)) {
			echo "Create database success<br />";
		} else {
			echo "Could not create database: " . mysql_error();
			return !$con;
		}
		return $con;
	}
	
	//create user table
	function table_usr_create_init($con, $dbname, $tablename)
	{
		if (!$con) {
			echo "Could not connect the database";
			return $con;
		}
		mysql_select_db($dbname, $con);
		$table_sql = "create table " . $tablename . 
		"(
		userid   long not NULL,
		username varchar(32),
		password varchar(32),
		email    varchar(64),
		valid    tinyint(1)
		)";
		if (mysql_query($table_sql, $con)) {
			echo "create usr table success<br />";
		} else {
			echo "Could not create teble: " . mysql_error();
			return !$con;
		}
		return $con;
	}
	
	//create admin table and insert a record into the table
	function table_admin_create_init($con, $dbname, $tablename)
	{
		if (!$con) {
			echo "Could not connect the database";
			return $con;
		}
		mysql_select_db($dbname, $con);
		$table_sql = "create table " . $tablename . 
		"(
		adminid int not NULL,
		adminname varchar(32),
		password  varchar(128),
		valid     tinyint(1)
		)";
		if (mysql_query($table_sql, $con)) {
			echo "create usr table success<br />";
		} else {
			echo "Could not create teble: " . mysql_error();
			return !$con;
		}
		$pass = md5("123456");
		$insert_sql = "insert into " . $tablename . "(adminid, adminname, password, valid)
		values (1, 'admin', '" . $pass . "', 1)";
		if (mysql_query($insert_sql, $con)) {
			echo "insert the admin success<br />";
		} else {
			echo "Could not create table: " . mysql_error();
			return !$con;
		}
		return $con;
	}
	
	$con = mysql_connect("localhost", "root", "");
	if (!$con) {
		die("Connect error, because of" . mysql_error());
	}
	
	if ($_POST["dbname"]) {
		db_create_init($con, $_POST["dbname"]);
	} 
	else
	{
		die("invalid dbname");
	}
	if ($_POST["table"]) {
		table_usr_create_init($con, $_POST["dbname"], $_POST["table"]);
	}
	else
	{
		echo "invalid table";
	}
	if ($_POST["admintable"]) {
		table_admin_create_init($con, $_POST["dbname"], $_POST["admintable"]);
	}
	else
	{
		echo "invalid admintable";
	}
	
	mysql_close($con);
?>
